<template>
  <el-row>
    <el-row class="loginContainer">
      <el-row class="loginContent">
        <el-row class="systemTitle"><img src="../../../src/assets/images/sys-name.png" alt=""></el-row>
        <el-row class="loginInfo">
          <el-col class="systemLogo" :span="10">
            <el-row><img src="../../../src/assets/images/home-icon.jpg" alt=""></el-row>
          </el-col>
          <!--登录-->
          <el-col v-show="flag==1" :span="12" class="loginInputInfo">
            <el-form :model="loginForm" label-width="100px" :rules="rules" ref="loginForm">
              <el-form-item label="手机号码：" prop="username">
                <el-input v-model="loginForm.username" size="small"></el-input>
              </el-form-item>
              <el-form-item label="密码：" prop="secretkey">
                <el-input v-model="loginForm.secretkey" size="small" type="password"></el-input>
              </el-form-item>
              <el-form-item>
                <el-col :span="6" ><el-button type="text" class="forgetPassword" @click="flag=2">忘记密码</el-button></el-col>
                <el-col :span="4" :offset="14"><el-button type="text" class="forgetPassword" @click="flag=3">注册</el-button></el-col>
              </el-form-item>
              <el-form-item>
                <el-button  class="loginBtn" @click="onLogin">登录</el-button>
              </el-form-item>
            </el-form>
          </el-col>
          <!--忘记密码-->
          <el-col v-show="flag==2" :span="12" class="changePwd">
            <el-button type="text">修改密码</el-button>
            <el-form ref="retrievePasswordForm" :model="retrievePasswordForm" label-width="110px" :rules="retrievePassword">
              <el-form-item label="手机号码：" prop="username">
                <el-input v-model="retrievePasswordForm.username" size="small"></el-input >
              </el-form-item>
              <el-form-item label="验证码：" prop="code">
                <el-col :span="14">
                  <el-input v-model="retrievePasswordForm.code" size="small"></el-input>
                </el-col>
                <el-col :span="10">
                  <el-button type="text" class="getCode" @click="getCode" :disabled="!show">
                    <span v-show="show">获取验证码</span>
                    <span v-show="!show" class="count">{{count}} s</span>
                  </el-button>
                </el-col>
              </el-form-item>
              <el-form-item label="新密码：" prop="newSecretkey">
                <el-input v-model="retrievePasswordForm.newSecretkey" size="small"></el-input>
              </el-form-item>
              <el-form-item label="再次输入密码：" prop="confirmSecretkey">
                <el-input v-model="retrievePasswordForm.confirmSecretkey" size="small"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="text" class="loginS" @click="flag=1">登录</el-button>
              </el-form-item>
              <el-form-item>
                <el-button class="loginBtn" @click="saveNewPassword">保存</el-button>
              </el-form-item>
            </el-form>
          </el-col>
          <!--注册-->
          <el-form ref="registerForm" :model="registerForm" label-width="110px" :rules="registerRules">
            <el-col v-show="flag==3" :span="12" class="loginInputInfo">
                <el-form-item >
                  <p class="hasUser">已有账号,<el-button type="text" class="loginRedirect" @click="flag=1">直接登录</el-button></p>
                </el-form-item >
                <el-form-item label="公司名称：" prop="companyName">
                  <el-input v-model="registerForm.companyName" size="small"></el-input>
                </el-form-item>
                <el-form-item label="用户姓名：" prop="name">
                  <el-input v-model="registerForm.name" size="small"></el-input>
                </el-form-item>
                <el-form-item label="营业执照：">
                  <input type="file" id="avata" ></input>
                </el-form-item>
                <el-form-item>
                  <el-button class="loginBtn" @click="goNextStep">下一步</el-button>
                </el-form-item>
            </el-col>
            <!--注册下一步-->
            <el-col v-if="flag==4" :span="12" class="changePwd">
              <el-button type="text" >注册</el-button>
                <el-form-item label="手机号码：" prop="username">
                  <el-input v-model="registerForm.username" size="small"></el-input >
                </el-form-item>
                <el-form-item label="验证码：" prop="code">
                  <el-col :span="14">
                    <el-input v-model="registerForm.code" size="small"></el-input>
                  </el-col>
                  <el-col :span="10">
                    <el-button type="text" class="getCode" @click="getCode" :disabled="!show">
                      <span v-show="show">获取验证码</span>
                      <span v-show="!show" class="count">{{count}} s</span>
                    </el-button>
                  </el-col>
                </el-form-item>
                <el-form-item label="密码：" prop="secretkey">
                  <el-input v-model="registerForm.secretkey"  size="small"></el-input>
                </el-form-item>
                <el-form-item label="再次输入密码：" prop="secretkeyAgain" label-width="110px">
                  <el-input v-model="registerForm.secretkeyAgain"  size="small"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="text" class="loginS" @click="flag=1">登录</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button size="small" class="goStep" @click="flag=3">上一步</el-button>
                    <el-button size="small" class="goStep" @click="register">注册</el-button>
                </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </el-row>
    </el-row>
  </el-row>
</template>
<script>
  import ElButton from "../../../node_modules/element-ui/packages/button/src/button.vue";
  import  axios from  'axios';
  import ElInput from "../../../node_modules/element-ui/packages/input/src/input.vue";
  const TIME_COUNT = 60;
  export default {
    components: {
      ElInput,
      ElButton},

    data() {
      // 验证手机号
      var validatePhone = (rule, value, callback) => {
        if (!(/^1[3|4|5|8][0-9]\d{4,8}$/.test(value))) {
          callback(new Error('手机号不合法!'));
        } else {
          callback();
        }
      };
      // 验证两次输入的密码 注册
      var validatePass2 = (rule, value, callback) => {
      if (value !== this.registerForm.secretkey) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      // 验证两次输入的密码 忘记密码
      var validatePass = (rule, value, callback) => {
        if (value !== this.retrievePasswordForm.newSecretkey) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        flag:1,
        //注册表单
        registerForm:{
          companyName:"",
          name:"",
          username:'',
          code:'',
          secretkey:'',
          secretkeyAgain:'',
          imageFiles : ''
        },
        show: true,
        count: '',
        timer: null,
        //登录
        loginForm: {
          username: '',
          secretkey:''
        },
        //忘记密码
        retrievePasswordForm:{
          username:'',
          code:'',
          newSecretkey:'',
          confirmSecretkey:''
        },
        //验证登录
        rules:{
          username:[
            {required:true,message:"请输入电话号码",trigger:'blur,change'},
            { validator: validatePhone, trigger: 'blur' }
          ],
          secretkey:[
            { required: true, message: '请输入密码', trigger: 'blur' },
          ],
        },
        //验证注册
        registerRules:{
          companyName:[
            {required:true,message:"请输入公司名称",trigger:'blur'}
          ],
          name:[
            { required: true, message: '请输入用户姓名', trigger: 'blur' },
          ],
          username:[
            { required: true, message: '请输入手机号码', trigger: 'blur,change' },
            { validator: validatePhone, trigger: 'blur' }
          ],
          code:[
            { required: true, message: '请输入验证码', trigger: 'blur' },
          ],
          secretkey:[
            { required: true, message: '请输入密码', trigger: 'blur' },
          ],
          secretkeyAgain:[
            { required: true, message: '请再次输入密码', trigger: 'blur' },
            { validator: validatePass2, trigger: 'blur' }
          ],
        },
        //忘记密码
        retrievePassword:{
          username:[
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { validator: validatePhone, trigger: 'blur' }
          ],
          code:[
            { required: true, message: '请输入验证码', trigger: 'blur' },
          ],
          newSecretkey:[
            { required: true, message: '请输入密码', trigger: 'blur' },
          ],
          confirmSecretkey:[
            { required: true, message: '请再次输入密码', trigger: 'blur' },
            { validator: validatePass, trigger: 'blur' }
          ],
        },
        imageUrl: ''
      }
    },
    methods: {
      //登录
      onLogin() {
        let self = this;
        this.$refs['loginForm'].validate((valide)=>{
          if(valide){
            var url = "/api/account/user/nologin/webLogin"
            // 封装form表单
            var data = new FormData();
            var reqData = {
              username : this.loginForm.username.trim(),
              secretkey : this.loginForm.secretkey.trim()
            }
            for(var key in reqData){
              data.append(key,reqData[key])
            }
            // 开始请求
            axios.post(url,data,{
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
              }
            }).then(function ({data}) {
                if(data.status){
                  console.log(data)
                  sessionStorage.setItem("token",data.data.token);
                  sessionStorage.setItem("webWsToken",data.data.webWsToken);
                  sessionStorage.setItem("name",data.data.name);
                  sessionStorage.setItem("username",data.data.username);
                  sessionStorage.setItem("userId",data.data.userId);
                  sessionStorage.setItem("userId",data.data.companyId);
                  self.$router.push('/main/client')
                }else{
                  self.$message.error(data.message);
                }
            })
          }
        })
      },
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      /*
       * 获取验证码
       */
      getCode(){
        // 验证码倒计时60s
        if (!this.timer) {
          this.count = TIME_COUNT;
          this.show = false;
          this.timer = setInterval(() => {
            if (this.count > 0 && this.count <= TIME_COUNT) {
              this.count--;
            } else {
              this.show = true;
              clearInterval(this.timer);
              this.timer = null;
            }
          }, 1000)
        }
        var url = "/api/commons/mobilePhoneCode/send"
        // 封装form表单
        var data = new FormData();
        var imagefile = document.getElementById("avata").files[0]
        var reqData = {
          mobilePhone : this.registerForm.username,
        }
        for(var key in reqData){
          data.append(key,reqData[key])
        }
        // 开始请求
        axios.post(url,data,{
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        })
          .then(function (response) {
            console.log(response);
          })
          .catch(function (response) {
            console.log(response);
          });
      },
      /*
       * 注册
       */
      goNextStep(){
        var that = this;
        that.$refs.registerForm.validate((valide)=>{
          if(valide){
            that.flag = 4
          }
        })
      },
      register() {
        var that = this;
        that.$refs['registerForm'].validate((valide)=>{
          if (valide) {
            var url = "/api/account/company/register"
            // 封装form表单
            var data = new FormData();
            var imagefile = document.getElementById("avata").files[0]
            var reqData = {
              companyName : this.registerForm.companyName,
              name : this.registerForm.name,
              username : this.registerForm.username,
              code : this.registerForm.code,
              secretkey : this.registerForm.secretkey,
              "imageFiles[]" : imagefile,
            }
            for(var key in reqData){
              data.append(key,reqData[key])
            }
            // 开始请求
            axios.post(url,data,{
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
              }
            })
            .then(function ({status,data}) {
               if(data.status){
                 that.$message.success("注册成功")
               }else{
                 that.$message.error(data.message)
               }
            })
          }
        })
      },

      //忘记密码
      saveNewPassword(){
        var that = this;
        that.$refs['retrievePasswordForm'].validate((valide)=>{
          if (valide) {
            var url = "/api/account/user/nologin/retrievePassword"
            // 封装form表单
            var data = new FormData();
            var reqData = {
              username : this.retrievePasswordForm.username,
              code : this.retrievePasswordForm.code,
              newSecretkey : this.retrievePasswordForm.newSecretkey,
              confirmSecretkey : this.retrievePasswordForm.confirmSecretkey,
            }
            for(var key in reqData){
              data.append(key,reqData[key])
            }
            // 开始请求
            axios.post(url,data,{
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
              }
            })
              .then(function ({data}) {
                if(data.status==true){
                  that.$message.success("保存成功")
                }else{
                  that.$message.error(data.message)
                }
              })
          }
        })
      }
    }
  }
</script>
<style scope>
  .loginContainer{
    background-image: url("../../../src/assets/images/bg.jpg");
    background-size: cover;
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .loginContent{
    display: flex;
    position: relative;
    width: 750px;
    height: 440px;
    text-align: center;
    background-color: white;
  }
  .systemTitle{
    position: absolute;
    top: -60px;
    text-align: center;
    left: 140px;
  }
  .loginInfo{
    width: 750px;
    height: 440px;
    background-color: white;
    position: absolute;
  }
  .changePwd{
    height: 100%;
    margin-top:25px;
  }
  .systemLogo{
    height: 100%;
  }
  .systemLogo>div{
    margin-top: 160px;
  }
  .loginInputInfo{
    height: 100%;
    margin-top:80px;
  }
  .forgetPassword{
    font-size:14px;
    color: #4fa7f9;
    text-decoration: none;
  }
  .loginBtn{
    background-color: #ffa44c;
    width: 90%;
    border: none;
    color: white;
  }
  .goStep{
    background-color: #ffa44c;
    border: none;
    color: white;
  }
  .getCode{
    width: 80%;
    height: 40px;
    border-radius: 5px;
    outline: none;
    border: none;
    color: #fff;
    background-color: lightgrey;
    font-size: 12px;
    margin-left: 22px;
  }
  .loginS{
    float:right;
  }
  /*上传营业执照*/
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 265px;
    height: 116px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .avatar-uploader-icon{
    line-height: 116px;
  }
  .el-form-item__label{
    padding: 0px;
  }
</style>
